<html>
<head>
<title>CS 143 Query</title>
</head>

Enter a valid SQL statement to be executed.

<p>
<form method="post">
<textarea name="input" cols="60" rows="8">
</textarea>
<input type="submit" value="Query" />
</form>
</p>

<body>
<?php
function evaluate($input)
{
	$db_connection = mysql_connect("localhost", "cs143", "");
	if(!$db_connection) 
	{
		print "Connection to Database Failed!: " . mysql_error($db_connection);
		exit(1);
	}

	mysql_select_db("CS143", $db_connection);
	$rs = mysql_query($input, $db_connection);

	mysql_close($db_connection);

	return $rs;
}

echo "The result of your query is: ";
$rs = evaluate($_POST["input"]);

$numrows = mysql_num_rows($rs);
$numcols = mysql_num_fields($rs);

if($numrows == 0 || $numcols == 0)
{
	echo "No result to display";
}
else
{
	$out = "<table border=1>\n";
	$out .= "<tr>\n";

	for($i = 0; $i < $numcols; $i++)
	{
		$out .= "<td>" . mysql_field_name($rs, $i) . "</td>\n";
	}
	$out .= "</tr>\n";

	while($row = mysql_fetch_row($rs))
	{
		$out = $out . "<tr> \n";
		foreach($row as $val)
		{
			$out = $out . "<td>" . $val . "</td>\n";
		}
		$out = $out . "</tr>\n";
	}

	echo $out;
}

?>

</body>
</html>
